<!--
 * @Author: zhuxiaoyi
 * @Date: 2024-01-10 18:37:27
 * @LastEditor: zhuxiaoyi
 * @LastEditTime: 2025-04-03 16:44:37
 * @Description: 
-->

<template>
    <el-row>
        <el-col :span="24" style="padding: 20px">
            <el-row>
                <el-col :span="24">
                    <el-card class="graph-container" :style="`height:${view.height - 195}px; box-sizing: border-box`">
                        <el-row class="graph-head">
                            <el-col :span="24">
                                <el-page-header style="margin-bottom: 10px;" @back="goBack">
                                    <template #content>
                                        <p v-if="nameStatus" style="display:flex;align-items:center">
                                            <span style="margin:0 10px 0 0;font-size: 14px;"> {{ currentGraph.name }}
                                            </span>
                                        </p>
                                    </template>
                                    <template #extra>
                                        <div class="flex items-center">
                                            <el-popover placement="bottom-end" :width="500">
                                                <template #reference>
                                                    <el-button type="primary" :size="'small'" plain :icon="Operation">
                                                        模板字符串</el-button>
                                                </template>
                                                <el-row>
                                                    <el-col :span="24"
                                                        style="display: flex;justify-content: space-between;">
                                                        <span style="font-size: 12px;font-weight: 600;">
                                                            模板字符串预设
                                                        </span>
                                                        <div>
                                                            <el-button type="primary" size="small" link
                                                                v-if="!dynamicEdit" @click="editDynamicHandler">
                                                                编辑</el-button>
                                                            <el-button type="primary" size="small" link
                                                                v-if="dynamicEdit" @click="saveDynamicData">
                                                                保存</el-button>
                                                            <el-button size="small" link @click="closeDynamicHandler">
                                                                取消</el-button>
                                                        </div>
                                                    </el-col>

                                                </el-row>
                                                <el-table stripe size="small" :data="dynamicData"
                                                    style="margin-top: 10px;">
                                                    <el-table-column label="参数名">
                                                        <template #default="{ row }">
                                                            <span style="font-weight: 600;" :title="row.name"
                                                                v-if="!dynamicEdit">
                                                                {{ row.name }}
                                                            </span>
                                                            <span style="font-weight: 600;" :title="row.name"
                                                                v-if="dynamicEdit">
                                                                <el-input size="small" v-model="row.name"></el-input>
                                                            </span>
                                                        </template>
                                                    </el-table-column>
                                                    <el-table-column label="参数值">
                                                        <template #default="{ row }">
                                                            <span style="font-weight: 600;" :title="row.value"
                                                                v-if="!dynamicEdit">
                                                                {{ row.value }}
                                                            </span>
                                                            <span style="font-weight: 600;" :title="row.value"
                                                                v-if="dynamicEdit">
                                                                <el-input size="small" v-model="row.value"></el-input>
                                                            </span>
                                                        </template>
                                                    </el-table-column>
                                                    <el-table-column width="60" :align="'center'" label="操作">
                                                        <template #default="scope">
                                                            <el-button size="small" link type="danger"
                                                                @click="removeDynamicData(scope.$index)">
                                                                删除
                                                            </el-button>
                                                        </template>
                                                    </el-table-column>
                                                </el-table>
                                                <el-row style="margin-top: 10px;">
                                                    <el-col :span="24">
                                                        <el-button style="width: 100%;" @click="addDynamicData">
                                                            新增
                                                        </el-button>
                                                    </el-col>
                                                </el-row>
                                            </el-popover>
                                            <el-popconfirm title="确定要执行当前流程?" @confirm="executeGraph">
                                                <template #reference>
                                                    <el-button type="success" size="small"
                                                        :icon="VideoPlay">开始执行</el-button>
                                                </template>
                                            </el-popconfirm>
                                        </div>
                                    </template>
                                </el-page-header>
                            </el-col>
                        </el-row>
                        <div id="container" :style="`height:${view.height - 255}px;`"></div>
                        <TeleportContainer />
                    </el-card>
                </el-col>
            </el-row>

            <el-drawer style="box-shadow: none;" v-model="paramsDrawer" :with-header="false" :modal="true">
                <el-row>
                    <el-col :span="24" v-loading="paramsLoading">
                        <el-card :style="`height:${view.height - 45}px;`">
                            <template #header>
                                <div>
                                    <el-row style="margin-bottom: 10px;">
                                        <el-col :span="24"
                                            style="display: flex;align-items: center; font-size: 14px;font-weight: 600;"
                                            :title="currentNodeLabel">
                                            <el-icon style="font-size: 20px;">
                                                <ElementPlus />
                                            </el-icon>
                                            &nbsp;
                                            <span>
                                                {{ currentNodeLabel }}
                                            </span>
                                        </el-col>
                                    </el-row>
                                    <el-row>
                                        <el-col :span="24" style="display: flex;justify-content: space-between;">
                                            <span style="color: #999;"> {{ currenNodeId }}</span>
                                            <div style="display: flex;align-items: center;">
                                                执行时暂停&nbsp; &nbsp;
                                                <el-radio-group v-model="currentNodePause" size="small">
                                                    <el-radio-button @click="changePauseStatus(true)" label="是"
                                                        :value="true" />
                                                    <el-radio-button type="danger" @click="changePauseStatus(false)"
                                                        label="否" :value="false" />
                                                </el-radio-group>
                                            </div>
                                        </el-col>
                                    </el-row>
                                    <el-row v-if="currentNodeLabel == '通用算法批量处理_batch_general'">
                                        <el-col :span="24"
                                            style="display: flex;justify-content: space-between;padding-top: 10px;">
                                            <div style="display: flex;align-items: center;">
                                                并行处理&nbsp; &nbsp;
                                                否&nbsp; &nbsp;
                                                <el-switch v-model="Parallel" @change="switchChangeHadler"
                                                    style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949" />&nbsp;
                                                &nbsp;
                                                是
                                            </div>
                                            <div>
                                                并行数&nbsp; &nbsp; <el-input-number v-model="num" :disabled="!Parallel"
                                                    :min="1" :max="1000" @change="changeParallel(num)" />
                                            </div>
                                        </el-col>
                                    </el-row>
                                </div>
                            </template>
                            <el-descriptions :style="`height:${view.height - 245}px; overflow:auto`"
                                direction="vertical" class="margin-top" :column="1" :size="'small'" :title="'参数预览'"
                                :border="true">
                                <template #extra>
                                    <el-button v-show="!editStatus" size="small" type="primary"
                                        @click="editAllParamsHandler">编辑参数</el-button>
                                    <el-button v-show="editStatus" size="small" type="primary"
                                        @click="exitEditMode">退出编辑</el-button>
                                    <el-button size="small" type="success" @click="saveParams">保存参数</el-button>
                                </template>
                                <el-descriptions-item v-for=" item in runTimeParams">
                                    <template #label>
                                        <div class="cell-item">
                                            {{ item.param_name }}({{ item.zh_name }})
                                        </div>
                                    </template>
                                    <div v-if="!item.editable">
                                        <div v-if="!item.form_type"
                                            style="display:flex;justify-content: space-between;">
                                            <el-tag v-if="item.default_value">
                                                {{ item.default_value }}
                                            </el-tag>
                                            <span v-if="!item.default_value">
                                                暂未填写...
                                            </span>
                                        </div>
                                        <div v-if="item.form_type == 'File'"
                                            style="display:flex;justify-content: space-between;">
                                            <el-tag v-if="item.default_value">
                                                {{ item.default_value }}</el-tag>
                                            <span v-if="!item.default_value">
                                                暂未填写...
                                            </span>
                                        </div>
                                        <el-card v-if="item.form_type == 'Files'" class="files-card">
                                            <div class="tag-container">
                                                <el-tag size="small" v-for=" (tag, index) in item.default_value"
                                                    :key="index">
                                                    {{ tag }}
                                                </el-tag>
                                            </div>
                                        </el-card>
                                        <el-select v-if="item.form_type == 'algorithm'" v-model="item.default_value"
                                            placeholder="Select" size="small" style="width: 240px" readonly disabled>
                                            <el-option v-for="option in algorithmOptions" :key="item.value"
                                                :label="option.label" :value="option.value" />
                                        </el-select>
                                        <div v-if="item.form_type == 'Dir'"
                                            style="display:flex;justify-content: space-between;">
                                            <el-tag v-if="item.default_value">{{ item.default_value
                                                }}</el-tag>
                                            <span v-if="!item.default_value">
                                                暂未填写...
                                            </span>
                                        </div>
                                        <div v-if="item.form_type == 'NewFile'"
                                            style="display:flex;justify-content: space-between;">
                                            <el-tag v-if="item.default_value">{{ item.default_value
                                                }}</el-tag>
                                            <span v-if="!item.default_value">
                                                暂未填写...
                                            </span>
                                        </div>

                                        <div v-if="item.form_type == 'runtimeParams'">
                                            <el-row>
                                                <el-col :span="8" v-for=" param in item.default_value"
                                                    style="padding: 0 5px" v-show="param.param_name != 'AlgoName'">
                                                    <el-row>
                                                        <el-col :span="24" style="padding: 10px 0 5px;">
                                                            {{ param.param_name }}({{ param.zh_name
                                                            }})
                                                        </el-col>
                                                        <el-col :span="24">
                                                            <el-input size="small" v-model="param.default_value"
                                                                :placeholder="`请输入${param.param_name}(${param.zh_name})`" />
                                                        </el-col>
                                                    </el-row>
                                                </el-col>
                                            </el-row>
                                        </div>
                                    </div>
                                    <div v-if="item.editable" style="display: flex">
                                        <el-input v-if="!item.form_type" :prefix-icon="EditPen"
                                            v-model="item.default_value" size="small"></el-input>
                                        <el-input v-if="item.form_type == 'File'" :prefix-icon="EditPen"
                                            v-model="item.default_value" size="small"></el-input>
                                        <el-card v-if="item.form_type == 'Files'" class="files-card">
                                            <template #header>
                                                <div class="card-header">
                                                    <el-button @click="openFolderHandler(item)" type="primary" plain
                                                        size="small" :icon="FolderOpened"></el-button>
                                                </div>
                                            </template>
                                            <div class="tag-container">
                                                <el-tag size="small" v-for=" (tag, index) in item.default_value"
                                                    :key="index" closable :disable-transitions="false"
                                                    @close="handleClose(item.default_value, tag)">
                                                    {{ tag }}
                                                </el-tag>
                                            </div>
                                        </el-card>
                                        <el-select v-if="item.form_type == 'algorithm'" v-model="item.default_value"
                                            placeholder="Select" size="small" style="width: 240px"
                                            @change="algorithmChangeHandler">
                                            <el-option v-for="option in algorithmOptions" :key="item.value"
                                                :label="option.label" :value="option.value" />
                                        </el-select>
                                        <el-input v-if="item.form_type == 'Dir'" :prefix-icon="EditPen"
                                            v-model="item.default_value" size="small"></el-input>
                                        <el-input v-if="item.form_type == 'NewFile'" :prefix-icon="EditPen"
                                            v-model="item.default_value" size="small"></el-input>
                                        <div v-if="item.form_type == 'runtimeParams'">
                                            <el-row>
                                                <el-col :span="12" v-for=" param in item.default_value"
                                                    v-show="param.param_name != 'AlgoName'" style="padding: 0 5px">
                                                    <el-row>
                                                        <el-col :span="24" style="padding: 10px 0 5px;">
                                                            {{ param.param_name }}({{ param.zh_name
                                                            }})
                                                        </el-col>
                                                        <el-col :span="24">
                                                            <el-input size="small" v-model="param.default_value"
                                                                :placeholder="`请输入${param.param_name}(${param.zh_name})`" />
                                                        </el-col>
                                                    </el-row>
                                                </el-col>
                                            </el-row>
                                        </div>

                                        <el-button v-if="item.form_type !== 'Files'" @click="openFolderHandler(item)"
                                            type="primary" plain size="small" :icon="FolderOpened"></el-button>
                                        <file-selection v-if="!item.form_type || item.form_type == 'File'"
                                            :inputData="item" :visible="item.visible"
                                            @closeFileDialog="closeFileDialogHandler" @dialogSubmit="fileSubmitHandler">
                                        </file-selection>
                                        <files-selection v-if="item.form_type == 'Files'" :inputData="item"
                                            :visible="item.visible" @closeFileDialog="closeFileDialogHandler"
                                            @dialogSubmit="filesSubmitHandler">
                                        </files-selection>

                                        <dirSelection v-if="item.form_type == 'Dir'" :inputData="item"
                                            :visible="item.visible" @closeFileDialog="closeFileDialogHandler"
                                            @dialogSubmit="dirSubmitHandler">
                                        </dirSelection>
                                        <newFile v-if="item.form_type == 'NewFile'" :inputData="item"
                                            :visible="item.visible" @closeFileDialog="closeFileDialogHandler"
                                            @dialogSubmit="dirSubmitHandler">
                                        </newFile>
                                    </div>

                                    <file-selection v-if="!item.form_type || item.form_type == 'File'" :inputData="item"
                                        :visible="item.visible" @closeFileDialog="closeFileDialogHandler"
                                        @dialogSubmit="fileSubmitHandler">
                                    </file-selection>
                                    <files-selection v-if="item.form_type == 'Files'" :inputData="item"
                                        :visible="item.visible" @closeFileDialog="closeFileDialogHandler"
                                        @dialogSubmit="filesSubmitHandler">
                                    </files-selection>
                                </el-descriptions-item>

                            </el-descriptions>
                            <template #footer>
                                <div style="display: flex; justify-content: flex-end;">
                                    <div v-if="currentNodeLabel == '成果展示(影像+矢量)_layers_preview'"
                                        style="display: flex;align-items: center;justify-content: flex-end;">
                                        <el-button color="#626aef" :disabled="currentNodeStatus != 'success'"
                                            :icon="HelpFilled" @click="openlayersHandler">成果可视化</el-button>
                                    </div>&emsp;
                                    <div v-if="currentNodeLabel == 'MPDI可视化成果推送_MPDI_product_push'"
                                        style="display: flex;align-items: center;justify-content: flex-end;">
                                        <el-button color="#626aef" :disabled="currentNodeStatus != 'success'"
                                            :icon="HelpFilled" @click="openlayersHandler1">成果可视化</el-button>
                                    </div>&emsp;
                                    <div v-if="currentNodeLabel == '矢量编辑(ArcGIS)_shp_edit'"
                                        style="display: flex;align-items: center;justify-content: flex-end;">
                                        <el-button type="success" :disabled="currentNodeStatus != 'pause'"
                                            :icon="HelpFilled" @click="openEditHandler">矢量编辑</el-button>
                                    </div>&emsp;
                                    <div v-if="currentNodePause"
                                        style="display: flex;align-items: center;justify-content: flex-end;">
                                        <el-button color="#626aef" :disabled="currentNodeStatus != 'pause'"
                                            :icon="HelpFilled" @click="continueToExcute(currenNodeId)">继续执行</el-button>
                                    </div>
                                </div>
                            </template>
                        </el-card>
                    </el-col>
                </el-row>
            </el-drawer>
        </el-col>
    </el-row>
</template>
<script setup lang="ts">
import { defineComponent, reactive, ref, toRefs, onMounted, watch, nextTick } from "vue";
// import * as _ from "lodash";
import { ElMessage, ElMessageBox } from "element-plus";
import axios from "axios";
import { Graph, Path, Cell, Edge, } from '@antv/x6'
import { Dnd } from "@antv/x6-plugin-dnd";
import { Selection } from "@antv/x6-plugin-selection";
import ProgressNode from "@/components/ProgressNode/ProgressNode.vue";
import { register, getTeleport } from "@antv/x6-vue-shape";
import HttpService from "@/api/api";
import { Search, CaretRight, Operation, Delete, InfoFilled, Edit, ArrowLeft, VideoPlay, Stopwatch, FolderChecked, Check, EditPen, HelpFilled, FolderOpened } from "@element-plus/icons-vue";
import { useRoute, useRouter } from "vue-router";
import { Scroller } from "@antv/x6-plugin-scroller";
import fileSelection from "@/components/fileSelection/fileSelectionRadio.vue";
import filesSelection from "@/components/fileSelection/fileSelectionCheckbox.vue";
import dirSelection from "@/components/fileSelection/dirSelection.vue"
import newFile from '@/components/fileSelection/newFile.vue'
import config from "@/config/config";

const router = useRouter()
const route = useRoute()
var graph, dnd;
let tableData = ref([])
let options = ref([])
let tableLoading = ref(false)
let keyword = ref('')
let nameStatus = ref(true)
let paramsDrawer = ref(false)
let editStatus = ref(false)
let dynamicEdit = ref(false)
let runTimeParams: any = ref([])
let currentNodeLabel = ref('')
let currentNodeStatus = ref('')
let currentNodePause = ref(false)
let currenNodeId = ref('')
let paramsLoading = ref(false)
let num = ref()
let Parallel = ref(true)
const currentGraph = reactive({
    id: "",
    name: "",
    graph: "",
    flow: "",
    dynamic: ""
})
const dynamicData = ref([])

const TeleportContainer = getTeleport();

register({
    shape: "custom-vue-node",
    width: 220,
    height: 56,
    component: ProgressNode,
    panning: true,
    mousewheel: {
        enabled: true,
        modifiers: ["ctrl", "meta"],
    },
    ports: {
        groups: {
            circle: {
                position: {
                    name: 'ellipseSpread',
                    args: {
                        compensateRotate: true,
                    },
                },
                attrs: {
                    circle: {
                        magnet: true,
                        stroke: "#8f8f8f",
                        r: 5,
                    },
                },
            },
        },
    },
});


let algorithmPagination = reactive({
    page_index: 1,
    page_size: 15,
    page_total: 0,
});

onMounted(() => {
    let container = document.getElementById("container");
    graph = new Graph({
        container: container,
        panning: {
            enabled: true,
            eventTypes: ["leftMouseDown"],
        },
        mousewheel: {
            enabled: true,
            modifiers: ["ctrl", "meta"],
        },
        background: {
            color: "#F2F7FA",
        },
        grid: {
            size: 10,
            visible: true,
            type: "doubleMesh",
            args: [
                {
                    color: "#eee", // 主网格线颜色
                    thickness: 1, // 主网格线宽度
                },
                {
                    color: "#ddd", // 次网格线颜色
                    thickness: 1, // 次网格线宽度
                    factor: 4, // 主次网格线间隔
                },
            ],
        },
    });

    graph.use(
        new Selection({
            multiple: true,
            rubberEdge: true,
            rubberNode: true,
            modifiers: "shift",
            rubberband: true,
        })
    );

    dnd = new Dnd({
        target: graph,
    });
    graph.use(
        new Scroller({
            enabled: true,
            pageVisible: true,
            pageBreak: true,
            pannable: true,
        })
    );

    graph.on('cell:click', ({ cell }) => {
        editStatus.value = false;
        paramsDrawer.value = true;
        let graphId = route.params.id
        currenNodeId.value = cell.id
        getAlgorithmParams(graphId, cell.id)
        getAlgorithmPauseStatus(graphId, cell.id)
        currentNodeLabel.value = cell.data.label
        currentNodeStatus.value = cell.data.status
        console.log(cell)

    })

    graph.on('cell:contextmenu', ({ cell }) => {
        console.log(cell.store.data)
    })

    getAlgorithm()
    initGraph()
});

const getAlgorithm = function () {
    let params = {
        page_size: algorithmPagination.page_size,
        page_index: algorithmPagination.page_index,
        keyword: keyword.value
    };
    tableData.value.length = 0;
    tableLoading.value = true
    HttpService.algorithmManage.getAlgorithms(
        params,
        (res) => {

            if (res.status == 200) {
                res.data.data.map((item, index) => {
                    tableData.value.push(item);
                    tableLoading.value = false
                });
                algorithmPagination.page_total = res.data.total
            } else {
                console.log("获取信息失败" + res);
                tableLoading.value = false
            }
        },
        (error) => {
            console.log(error);

            tableLoading.value = false
        }
    );
};


var view = reactive({
    height: window.innerHeight,
});
const algorithmOptions = ref([])

const getAllAlgorithm = function () {
    let params = {
        page_size: 1000,
        page_index: 1,
        keyword: ''
    };
    algorithmOptions.value.length = 0
    HttpService.algorithmManage.getAlgorithms(
        params,
        (res) => {

            if (res.status == 200) {
                res.data.data.map((item, index) => {
                    algorithmOptions.value.push(
                        {
                            value: item.id,
                            label: item.name,
                            parameter: item.parameter
                        }
                    );
                });
            } else {
                console.log("获取信息失败" + res);
            }
        },
        (error) => {
            console.log(error);
        }
    );
};

getAllAlgorithm()

const getProcess = function (id) {
    let params = {
        id
    };
    HttpService.processListManage.getProcess(
        params,
        (res) => {
            if (res.status == 200) {
                let graph = res.data.data
                Object.assign(currentGraph, graph)
                currentGraph.dynamic = JSON.parse(graph.dynamic)
                createGraphNode()
                getDynamicData()
            } else {
                console.log("获取信息失败" + res);
            }
        },
        (error) => {
            console.log(error);
        }
    );
}
const getDynamicData = function () {
    let params = {
        id: route.params.id
    };
    dynamicData.value.length = 0
    HttpService.processListManage.getDynamicData(
        params,
        (res) => {
            if (res.status == 200) {
                res.data.data & res.data.data.forEach((dynamic) => {
                    dynamicData.value.push(dynamic)
                })
            } else {
                console.log("获取信息失败" + res);
            }
        },
        (error) => {
            console.log(error);
        }
    );
}

const initGraph = async function () {
    let graphId = route.params.id
    if (graphId != 'newGraph' && graphId != undefined) {
        getProcess(graphId)
    } else {
        currentGraph.name = '未命名_算法流程_' + new Date().getTime()
    }
}

const createGraphNode = function () {
    graph.fromJSON(JSON.parse(currentGraph.graph))
}

const goBack = function () {
    router.push('/index/general/processManage/processList')
}


const enterToGraph = function (process) {
    router.push('/index/general/processManage/processGraph/' + process.id)
}

const getAlgorithmParams = function (graphId, nodeId) {
    let params = {
        graphId: graphId,
        id: nodeId
    };
    paramsLoading.value = true;
    runTimeParams.value.length = 0
    HttpService.processListManage.getAlgorithmParams(
        params,
        (res) => {
            if (res.status == 200) {
                setTimeout(() => {
                    let resData = res.data.data
                    let currentParams = JSON.parse(resData.runTimeParams)
                    currentParams.forEach(element => {
                        element.editable = false;
                        runTimeParams.value.push(element)
                    });
                    // runTimeParams.value.length = 0

                    paramsLoading.value = false;
                }, 500)
            }
        },
        (error) => {
            paramsLoading.value = false;
            console.log(error);
        }
    );
}

const getAlgorithmPauseStatus = function (graphId, nodeId) {
    let params = {
        graphId: graphId,
        id: nodeId
    };
    HttpService.processListManage.getAlgorithmParams(
        params,
        (res) => {
            if (res.status == 200) {
                setTimeout(() => {
                    let resData = res.data.data
                    currentNodePause.value = resData.pause
                    num.value = resData.Parallel
                    console.log(currentNodePause)
                }, 500)
            }
        },
        (error) => {
            paramsLoading.value = false;
            console.log(error);
        }
    );
}


const editAllParamsHandler = function () {
    runTimeParams.value.forEach(element => {
        element.editable = true
    });
    // currentParameters.value.length = 0
    editStatus.value = true
}
const exitEditMode = function () {
    runTimeParams.value.forEach(element => {
        element.editable = false
    });
    editStatus.value = false
}

const saveParams = function () {
    let nodeParams = []
    runTimeParams.value.forEach(element => {
        element.editable = false
        let param = {
            param_name: element.param_name,
            default_value: element.default_value,
            zh_name: element.zh_name,
            form_type: element.form_type
        }
        nodeParams.push(param)
    });
    let graphId = route.params.id
    let node = {
        id: currenNodeId.value,
        runTimeParams: JSON.stringify(nodeParams)
    }
    updateNodeParams(graphId, node)
}

const updateNodeParams = function (graphId, node) {
    let params = {
        graphId: graphId,
        id: node.id,
        runTimeParams: node.runTimeParams
    };
    runTimeParams.value.length = 0
    HttpService.processListManage.updateNodeParams(
        params,
        (res) => {
            if (res.status == 200) {
                getAlgorithmParams(graphId, node.id)
                ElMessage({
                    message: "参数更新成功 ",
                    type: "success",
                });
            }
        },
        (error) => {
            console.log(error);
        }
    );
}

const executeGraph = function () {
    let graphId = route.params.id
    let params = {
        id: graphId
    };
    HttpService.processListManage.executeGraph(
        params,
        (res) => {
            if (res.status == 200) {
                ElMessage({
                    message: "流程开始执行 ",
                    type: "success",
                });
            } else {
                console.log("流程执行失败" + res);
            }
        },
        (error) => {
            console.log(error);
        }
    );
}


const socket = ref(null);
const isConnected = ref(false);

socket.value = new WebSocket(`ws://${config.socket_url}/webSocket`);
socket.value.onopen = () => {
    console.log('graph connected');
    isConnected.value = true;
};
socket.value.onmessage = async (event) => {
    const data = JSON.parse(event.data);
    const { cmd, action, graphId } = data
    if (cmd == 'graph') {
        console.log(graphId == route.params.id)
        if (graphId == route.params.id) {
            await getProcess(graphId)
        }
    }
};
socket.value.onclose = () => {
    console.log('graph disconnected');
    isConnected.value = false;
};



const openlayersHandler = function () {
    let graphId = route.params.id
    router.push(`/custom/${currenNodeId.value}?type=miniTask&graphId=${graphId}`)
}
const openlayersHandler1 = function () {
    router.push(`/bigScreen/11`)
}


const getStyles = function () {
    let params = {};
    options.value.length = 0;
    HttpService.sldManage.getStyles(
        params,
        (res) => {
            if (res.status == 200) {
                console.log(res.data);
                res.data.styles.style.map((item, index) => {
                    let option = {
                        value: item.name,
                        label: item.name,
                    }
                    options.value.push(option);
                });
            } else {
                console.log("获取信息失败" + res);
            }
        },
        (error) => {
            console.log(error);
        }
    );
};

let currentInput: any = reactive({})
const openFolderHandler = function (param) {
    param.visible = true
    currentInput = param
}

const closeFileDialogHandler = function () {
    currentInput.visible = false
    // currentInput.default_value = value
    // currentInput.
}

const filesSubmitHandler = function (data) {
    let files = []
    data.value.forEach(item => {
        files.push(item.fullPath)
    })
    currentInput.default_value = files
    console.log(currentInput.default_value)
}
const fileSubmitHandler = function (data) {
    currentInput.default_value = data.value.fullPath
    console.log(currentInput.default_value)
}
const handleClose = (tags, tag: string) => {
    tags.splice(tags.indexOf(tag), 1)
}
const algorithmChangeHandler = function (algorithmId) {
    runTimeParams.value.forEach(item => {
        if (item.form_type == 'runtimeParams') {
            getAlgorithmById(algorithmId, item)
        }
    })
}

const getAlgorithmById = function (algorithmId, runtimeParams) {
    let params = {
        id: algorithmId
    };
    runtimeParams.default_value = []
    HttpService.algorithmManage.getAlgorithmById(
        params,
        (res) => {

            if (res.status == 200) {
                let algorithm = res.data.data
                JSON.parse(algorithm.parameters).forEach(parameter => {
                    console.log(parameter)
                    if (parameter.param_name !== "inputFile" && parameter.param_name !== "outputFile") {
                        runtimeParams.default_value.push(parameter)
                    }
                })
            } else {
                ElMessage({
                    message: res,
                    type: "error",
                });
            }
        },
        (error) => {
            console.log(error);
        }
    )
}
const dirSubmitHandler = function (data) {
    currentInput.default_value = data
}

const editDynamicHandler = function () {
    dynamicEdit.value = true
}
const closeDynamicHandler = function () {
    dynamicEdit.value = false
    getDynamicData()
}
const removeDynamicData = function (index) {
    dynamicData.value.splice(index, 1)
    dynamicEdit.value = true
}
const addDynamicData = function () {
    dynamicData.value.push({ name: '', value: "" })
    dynamicEdit.value = true
}

const saveDynamicData = function () {
    let params = {
        id: route.params.id,
        dynamicData: dynamicData.value
    };
    HttpService.processListManage.editDynamicData(
        params,
        (res) => {
            if (res.status == 200) {
                closeDynamicHandler()
            } else {
                console.log("获取信息失败" + res);
            }
        },
        (error) => {
            console.log(error);
        }
    );
}

const changePauseStatus = function (status) {
    let params = {
        graphId: route.params.id,
        id: currenNodeId.value,
        status: status
    };
    HttpService.processListManage.changePauseStatus(
        params,
        (res) => {
            if (res.status == 200) {
                setTimeout(() => {
                    getAlgorithmPauseStatus(params.graphId, params.id)
                    ElMessage({
                        message: '状态修改成功',
                        type: "success",
                    });
                }, 300)
            } else {
                ElMessage({
                    message: res,
                    type: "error",
                });
            }
        },
        (error) => {
            console.log(error);
        }
    );
}
const changeParallel = function (num) {
    let params = {
        graphId: route.params.id,
        id: currenNodeId.value,
        Parallel: num
    };
    HttpService.processListManage.changeParallel(
        params,
        (res) => {
            if (res.status == 200) {
                setTimeout(() => {
                    getAlgorithmPauseStatus(params.graphId, params.id)
                    ElMessage({
                        message: '并行数修改成功',
                        type: "success",
                    });
                }, 300)
            } else {
                ElMessage({
                    message: res,
                    type: "error",
                });
            }
        },
        (error) => {
            console.log(error);
        }
    );
}

const continueToExcute = function (id) {
    let params = {
        id,
    };
    HttpService.processListManage.continueToExcute(
        params,
        (res) => {
            if (res.status == 200) {
                ElMessage({
                    message: '流程继续执行',
                    type: "success"
                });
                paramsDrawer.value = false;
            } else {
                ElMessage({
                    message: res,
                    type: "error"
                });
            }
        },
        (error) => {
            console.log(error);
        }
    );

}

let originalValue = num.value; // 保存原始值

const switchChangeHadler = (status) => {
    if (status) {
        // 恢复为原始值
        num.value = originalValue;
        changeParallel(num.value)
    } else {
        // 保存当前值作为原始值，并设置为1
        originalValue = num.value;
        num.value = 1;
        changeParallel(num.value)
    }
};

/* const openEditHandler = function () {
    let params = {
        shp_path: runTimeParams.value[1].default_value,
        temp_path: runTimeParams.value[2].default_value,
        mxd_path: runTimeParams.value[3].default_value
    }
    let url = `app://${encodeURIComponent(JSON.stringify(params))}`;
    console.log(JSON.stringify(params))
    window.open(url); // 打开新窗口或标签
} */

const openEditHandler = function () {
    // 获取参数
    let params = {
        shp_path: runTimeParams.value[1].default_value,
        temp_path: runTimeParams.value[2].default_value,
        mxd_path: runTimeParams.value[3].default_value
    };
    
    console.log("调用ArcGIS处理，参数:", params);
    
    // 序列化为JSON并去除可能的特殊字符
    let jsonParams = JSON.stringify(params).replace(/\\/g, '');
    
    // 创建URL格式参数，确保没有末尾斜杠
    let encodedParams = encodeURIComponent(jsonParams);
    let appUrl = `app://${encodedParams}`;
    
    console.log("生成的URL:", appUrl);
    
    // 直接使用window.open打开自定义协议URL
    try {
        window.open(appUrl);
    } catch(e) {
        console.error("打开URL失败:", e);
        alert("启动ArcGIS处理失败，请确保已正确配置应用程序协议处理器。");
    }
};
/* window.onresize = _.debounce(() => {
    view.height = window.innerHeight;
}, 100); */
getStyles()
</script>
<style lang="scss" scoped>
#container {
    height: 600px;
}
</style>
<style lang="scss">
.x6-node-selected .pennding {
    border-color: #1890ff;
    border-radius: 2px;
    box-shadow: 0 0 0 4px #d4e8fe;
}

.x6-node-selected .running {
    border-color: #E6A23C;
    border-radius: 2px;
    box-shadow: 0 0 0 4px #e6d4ba;
}

.x6-node-selected .success {
    border-color: #52c41a;
    border-radius: 2px;
    box-shadow: 0 0 0 4px #ccecc0;
}

.x6-node-selected .failed {
    border-color: #ff4d4f;
    border-radius: 2px;
    box-shadow: 0 0 0 4px #fedcdc;
}

.x6-node-selected .pause {
    border-color: #CBAEFF;
    border-radius: 2px;
    box-shadow: 0 0 0 4px rgba(254, 220, 220, 0.5);
}

.graph-head {
    .el-page-header__back {
        color: #fff;
    }
}

.graph-container {

    .el-card__body {
        padding: 15px;
    }

}

.files-card {
    .el-card__header {
        padding: 5px;

        .head {
            width: 100%;
            display: flex;
            justify-content: flex-end;
        }
    }
}
</style>
